package com.tlr.device.rest;

import java.util.List;

import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tfb.rong.Device;
import com.tfb.rong.Response;
import com.tfb.rong.Users;
import static com.tfb.service.utility.HttpUtil.getUserDBID;
import com.tfb.service.utility.Utils;
import com.tlr.device.model.Result;
import com.tlr.device.service.DeviceDatabaseService;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
import org.apache.log4j.Logger;

@Path("/general_device")
public class DeviceResource {

    private static final Logger log = Logger.getLogger(DeviceResource.class);
    @Context
    ServletContext context;
    DeviceDatabaseService deviceService = null;

    private synchronized void initDatabaseService() {
        if (deviceService == null) {
            ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
            deviceService = (DeviceDatabaseService) ac.getBean("deviceDatabaseService");
        }
    }

    @Path("/add")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response addDevice(Device device) {
        initDatabaseService();
        Response rsp = new Response();
        if (deviceService.getDeviceByMac(device.getDevicemac()) != null) {
            rsp.setReturncode(-1);
            rsp.setMessage(device.getDevicemac() + " 设备已经存在");
        } else if (deviceService.addDevice(device) == 1) {
            rsp.setReturncode(0);
            rsp.setMessage("添加成功");
            rsp.setDevice(device);
        } else {
            rsp.setReturncode(-1);
            rsp.setMessage("添加失败");
        }
        return rsp;
    }

    @Path("/rename")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response renameDevice(Device device) {
        initDatabaseService();
        int ret = deviceService.updateDevice(device);
        Response rsp = new Response();
        if (ret == 1) {
            rsp.setReturncode(0);
            rsp.setMessage("modify device successfully");
        } else {
            rsp.setReturncode(-1);
            rsp.setMessage("fail to modify device");
        }
        return rsp;
    }

    @Path("/modify")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response modifyDevice(Device device) {
        initDatabaseService();
        Response rsp = new Response();
        log.info("device id: " + device.getDeviceid());
        if (device.getBinduser() != null && !device.getBinduser().isEmpty() && device.getDevicetype() == 2) {
            // one driver only bind one car if the type is car
            List<Device> dlist = deviceService.getAllBindDevice(device.getBinduser(), device.getDevicetype());
            if (!dlist.isEmpty() && !dlist.get(0).getDeviceid().equals(device.getDeviceid())) {
                rsp.setReturncode(-1);
                rsp.setMessage("一个司机只能绑定一辆服务车");
                return rsp;
            }
        }
        int ret = deviceService.modifyDevice(device);

        if (ret == 1) {
            rsp.setReturncode(0);
            rsp.setMessage("modify device successfully");
        } else {
            rsp.setReturncode(-1);
            rsp.setMessage("fail to modify device");
        }
        return rsp;
    }

    @Path("/del")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response delDevice(Device device) {
        initDatabaseService();
        int ret = deviceService.delDevice(device.getDeviceid());
        Response rsp = new Response();

        if (ret == 1) {
            rsp.setReturncode(0);
            rsp.setMessage("del device successfully");
        } else {
            rsp.setReturncode(-1);
            rsp.setMessage("fail to del device");
        }
        return rsp;
    }

    @Path("/list")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Device> listDevice(@QueryParam("device_type") int device_type) {
        initDatabaseService();
        if (device_type == 0) {
            return deviceService.getAllDevice();
        }
        return deviceService.getDevices(device_type);
    }

    @Path("/get_bind")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<Device> getBindDevice(@Context HttpServletRequest request, @QueryParam("mac") String mac) {
        try {
            initDatabaseService();
            String userID = getUserDBID(request);
            Device device = deviceService.getDeviceMapper().selectDeviceWithBindedInfoByUserIDAndDeviceMac(userID, mac);
            return new Result<>(0, "OK", device);
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "查询绑定用户错误，请联系管理员");
        }
    }

    @Path("binded_user")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Result<List<Users>> getBindedUsers(@QueryParam("device_mac") String deviceMac) {
        try {
            initDatabaseService();
            return new Result<>(0, "OK", deviceService.getUserMapper().selectByDeviceUserBind(deviceMac));
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "查询绑定用户错误，请联系管理员");
        }
    }

    @Path("del_bind")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    public Result<String> delBindHeathUser(@Context HttpServletRequest request,
                                           @QueryParam("device_mac") String deviceMac,
                                           @QueryParam("user_id") String userID) {
        try {
            if (userID == null || userID.isEmpty()) {
                userID = getUserDBID(request);
            }
            log.info("Deleting device user binding with[device_id: " + deviceMac + ", user_id: " + userID + "]");
            initDatabaseService();
            deviceService.getDeviceUserBindMapper().deleteByUserIDAndDeviceID(userID, deviceMac);
            return new Result<>(0, "OK");
        } catch (Exception e) {
            log.error(Utils.getFullException(e));
            return new Result<>(500, "删除失败，请联系管理员");
        }
    }
}
